import { Command } from '../constant';
import { Dispatch } from 'typings';
import Taro from '@tarojs/taro';
import { getActionProxy } from '@/redux/action-util';
import * as reduxStore from '@/redux/store';
import Action from './action';
import packageDServiceCentre from '../reducers/main';
import api from 'api';

export default (dispatch?: Dispatch) => {
  const actions = {
    action: getActionProxy<typeof Action>(Action)(dispatch),

    /**
     * 初始化数据
     */
    async init(memberType: number | string) {
      await actions.loadReducer();
      // 发送请求 - 自行判断是否try catch
      const res = await api.customerSignRecordController.getCustomerInfo();
      Taro.setStorageSync('isAquamarineMember', res.customerVO.isAquamarineMember);
      Taro.setStorageSync('isCrystalMember', res.customerVO.isCrystalMember);
      // 初始化赋值 后续使用 action 中的commonChange方法改变值
      dispatch({
        type: Command.init,
        payload: {
          main: {
            customerId: res.customerVO.customerId,
            isAquamarineMember: res.customerVO.isAquamarineMember,
            isCrystalMember: res.customerVO.isCrystalMember,
          },
        },
      });
      await actions.action.page(memberType);
    },
    /**
     * 重置
     */
    async clean() {
      //@ts-ignore
      __TARO_ENV !== 'h5' && (await actions.unloadReducer());
      dispatch({ type: Command.clean });
    },

    /**
     * 动态添加注入reducer
     */
    async loadReducer() {
      reduxStore.registerReducer({
        packageDServiceCentre,
      });
    },

    /**
     * 卸载reducer
     */
    async unloadReducer() {
      if (reduxStore.deregister) {
        reduxStore.deregister(['packageDServiceCentre']);
      } else {
        console.error('请在redux/store中实现deregister逻辑. ');
      }
    },
  };

  return { actions };
};

//create by moon https://github.com/creasy2010/moon
